import { urlWork } from 'nui';
import { obj_str, for_obj } from 'sui';

const g_st = {
    "0": "WAIT",
    "1": "ACTIVE",
    "2": "DONE",
    "3": "DOING",
};

const is_array = (v) => {
    const r = Object.prototype.toString.call(v);
    return r === "[object Array]"
};

const is_object = (v) => {
    const r = Object.prototype.toString.call(v);
    return r === "[object Object]"
};

const set_array = (ret, data, pre="") => {
    data.forEach((v, i) => {
        const k = `${pre}.${i}`;

        if (is_object(v)) {
            set_obj(ret, v, k);
            return;
        }

        ret[k] = v;
    });
};

const set_obj = (ret, data, pre) => {
    for_obj(data, (k, v) => {
        let key = k;
        if (pre) {
            key = `${pre}.${k}`;
        }

        if (is_array(v)) {
            set_array(ret, v, key);
            return;
        }

        ret[key] = v;
    });
};

const load_real = (main, hok) => {
    const uid = obj_str(main, "uid");
    if (!uid) {
        return;
    }

    const m = obj_str(main, "m");

    const htr = (ret, hnext) => {
        if (!m) {
            return hnext();
        }

        urlWork(null, "real/get", {uid: `tr.${uid}.${m}`}, r => {
            ret[m] = r;
            hnext();
        }, e => hnext());
    };

    const hst = (ret, hnext) => {
        urlWork(null, "real/get", {uid: `st.${uid}`}, r => {
            const v = `${r}`;
            ret[uid] = g_st[v];

            hnext();
        }, e => hnext());
    };

    urlWork(null, "real/get", {uid: uid}, r => {
        const ret = {};

        for_obj(r, (k, v) => {
            if (is_object(v)) {
                set_obj(ret, v, k);
                return;
            }

            if (is_array(v)) {
                set_array(ret, v, k);
                return;
            }

            ret[k] = v;
        });

        htr(ret, () => hst(ret, () => hok(ret)))
    }, e => hok(null));
};

export {load_real};
